import local from '@/common/local.js'
import logger from '@/common/util/logger.js'
import serveRoots from "@/project/serveRoots.js"
import store from '@/store'
// req2 START
function post2(url, data = {}, options = {}) {
	return req2(url, data, {
		...options,
		method: 'POST',
	})
}

function get2(url, data = {}, options = {}) {
	return req2(url, data, {
		...options,
		method: 'GET',
	})
}

function req2(url, data = {}, options = {}) {
	const root = local.env.rootMap['http5']
	let authorization;
	try {
		authorization = store.state.User.userInfo.jxyUserInfo.token;
	} catch (e) {
		authorization = ''
	}
	const header = {
		authorization
	}
	Object.assign(header, options.header);
	return request(root, url, {
		...options,
		header,
		data
	})
}
// req2 END

// req1 START
function post1(url, data = {}, options = {}) {
	return req1(url, data, {
		...options,
		method: 'POST',
	})
}

function req1(url, data = {}, options = {}) {
	const root = local.env.rootMap['http5']
	const header = {}
	Object.assign(header, options.header);
	return request(root, url, {
		...options,
		header,
		data
	})
}
// req2 END

function request(root = '', url_, options = {}) {
	const url = local.env.server + root + serveRoots.prefixUrl+(ifObject(url_) ? url_.url : url_)
	const header = {
		SYS_SIGN: 'APP',
		'Content-Type': 'application/json;charset=UTF-8'
	}
	Object.assign(header, options.header)
	return new Promise((reslove, reject) => {
		uni.request({
				...options,
				url,
				header
			})
			.then(res => {
				if (res[0]) return Promise.reject(res[0])
				res = res[1];
				if (!checkStatusCode(res.statusCode)) return Promise.reject(res)
				if (typeof res.data === 'string') res.data = JSON.parse(res.data)
				if (res.data.code !== 200) return Promise.reject(res.data)
				if (res.data.status !== 1) return Promise.reject(res.data)
				reslove(res.data)
			}).catch(err => {
				reject(err)
				logger.error(err);
			})
	})
}

function checkStatusCode(statusCode) {
	return statusCode >= 200 && statusCode < 300 && statusCode != 201 && statusCode != 202 || statusCode === 304;
}

function ifObject(data) {
	return typeof data === 'object' && !Array.isArray(data) && data !== null;
}

module.exports = {
	post1,
	post2,
	get2,
}
